import { Application, ChannelService, RemoterClass, FrontendSession } from 'pinus';

export default function (app: Application) {
    return new ChatRemoter(app);
}

// UserRpc的命名空间自动合并
declare global {
    interface UserRpc {
        chat: {
            // 一次性定义一个类自动合并到UserRpc中
            chatRemoter: RemoterClass<FrontendSession, ChatRemoter>;
        };
    }
    // interface RemoterChat {
    //     chatRemoter: RemoterClass<FrontendSession, ChatRemoter>;
    // }

    // interface UserRpc {
    //     chat: RemoterChat;
    // }
}


export class ChatRemoter {
    constructor(private app: Application) {
        this.app = app;
        this.channelService = app.get("channelService");
    }

    private channelService: ChannelService;

    /** 把客户端添加到channel 
     * @param uid 用户的唯一id
     * @param sid 服务器id
     * @param name channel的名字
     * @param flag 如果该channel不存在，是否创建channel
     */
    public async add(uid: string, sid: string, name: string, flag: boolean) {

        //创建一个channel
        let channel = this.channelService.getChannel(name, flag);

        //将用户加入channel
        if (!!channel) {
            channel.add(uid, sid);
        }
        console.log("当前sid：",sid);
        console.log("当前channel里的成员: ", channel.getMembers());

        //把当前加入的客户端，广播给所有客户端
        let userName = uid.split("*")[0];
        let param = {
            user: userName
        }

        channel.pushMessage("onAdd", param);

        // try {
        //     channel.pushMessage("onAdd", param);
        // } catch (error) {
        //     console.log("错误信息：",error);
        // }
            

        //返回当前channel里所有的用户名字
        return this.getUsersName(name, flag);
    }

    /** 获取某个channel里的所有用户名字 
     * @param name channel的名字
     * @param flag 如果该channel不存在，是否创建channel
    */
    private getUsersName(name: string, flag: boolean) {

        let users: string[] = [];

        //获取指定的channel
        let channel = this.channelService.getChannel(name, flag);

        //获取指定channel里加入的所有客户端
        if (!!channel) {
            users = channel.getMembers();
        }

        //返回所有客户端的名字
        for (let i = 0, len = users.length; i < len; i++) {
            users[i] = users[i].split("*")[0];
        }
        return users;
    }

    /** 将客户端踢出channel
     * @param uid 用户的唯一id
     * @param sid 服务器id
     * @param name channel的名字
    */
    public async kick(uid: string, sid: string, name: string) {
        //获取指定的channel
        let channel = this.channelService.getChannel(name, false);

        //将指定客户端踢出channel
        if (!!channel) {
            channel.leave(uid, sid);
        }

        //通知当前channel里的所有客户端，说：某某离开了

    }
}